package com.atguigu.guli.service.ucenter.service.impl;

import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.base.helper.JwtHelper;
import com.atguigu.guli.service.base.helper.JwtInfo;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.ucenter.entity.Member;
import com.atguigu.guli.service.ucenter.service.MemberService;
import com.atguigu.guli.service.ucenter.service.WXloginService;
import com.atguigu.guli.service.ucenter.util.UcenterProperties;
import com.atguigu.guli.service.util.utils.HttpClientUtils;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.terracotta.management.model.cluster.ClientIdentifier;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j
public class WXloginServiceImpl implements WXloginService {
@Autowired
    MemberService memberService;
    @Autowired
    UcenterProperties ucenterProperties;
    @Override
    public String callback(String code, String state, HttpSession session) {
        //判断session中的值与state中的值一致
        Object attribute = session.getAttribute("state");
        if (attribute==null|| StringUtils.isEmpty(state)||!attribute.equals(state)){
            throw  new GuliException(ResultCodeEnum.UNKNOWN_REASON);
        }
        //移除session中的state
        session.removeAttribute("state");
        //根据code获取access_token
        if (StringUtils.isEmpty(code)){
            throw new GuliException(ResultCodeEnum.UNKNOWN_REASON);
        }
        try {
            String url  = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                    "appid=" +ucenterProperties.getAppId()+
                    "&secret=" +ucenterProperties.getAppSecret()+
                    "&code=" +code+
                    "&grant_type=authorization_code";
            //工具类实现地址的发送
            HttpClientUtils client = new HttpClientUtils(url);
            client.get();
            String content = client.getContent();
            Gson gson = new Gson();
            Map map = gson.fromJson(content, Map.class);
            if(map.get("errcode")!=null){
                log.error(content);
                throw new GuliException(ResultCodeEnum.UNKNOWN_REASON);
            }
            String access_token = map.get("access_token").toString();
            String openid = map.get("openid").toString();

            String newUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=" +access_token+
                    "&openid="+openid;
            HttpClientUtils newClient = new HttpClientUtils(newUrl);
            newClient.get();
            String clientContent = newClient.getContent();
            Map mapJson = gson.fromJson(clientContent, Map.class);
            if(mapJson.get("errcode")!=null){
                log.error(content);
                throw new GuliException(ResultCodeEnum.UNKNOWN_REASON);
            }
        //获取查询到的用户数据
            String nickname = mapJson.get("nickname").toString();
            String avatar = mapJson.get("headimgurl").toString();
            Integer sex = (int)(Double.parseDouble(mapJson.get("sex").toString()));

            Member newMember = new Member();
            newMember.setNickname(nickname);
            newMember.setAvatar(avatar);
            newMember.setOpenid(openid);
            newMember.setSex(sex);
            //保存用户数据到数据库
            //1、查询用户数据是否已经在数据库中
            LambdaQueryWrapper<Member> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Member::getOpenid,openid);
            Member member = memberService.getOne(queryWrapper);
            if (member==null){//不在数据库中，实现保存
                memberService.save(newMember);
                return changeJwt(newMember);

            }else if ((System.currentTimeMillis()-member.getGmtModified().getTime())>=24*3*60*60*1000){
                memberService.updateById(newMember);
             return  changeJwt(newMember);
            }
              return   changeJwt(member);

            //转换为jwt格式的字符串，传回前端页面

        } catch (Exception e) {
            throw new GuliException(ResultCodeEnum.UNKNOWN_REASON);
        }
    }

    @Override
    public String login(HttpSession session) {

        try {
            String URL = "https://open.weixin.qq.com/connect/qrconnect" +
                    "?appid=%s" +
                    "&redirect_uri=%s"+
                    "&response_type=code" +
                    "&scope=snsapi_login" +
                    "&state=%s" +
                    "#wechat_redirect";
            String redirectUrl = ucenterProperties.getRedirectUri();
            String state = UUID.randomUUID().toString().replace("-" , "");
            session.setAttribute("state",state);
            URL = String.format(URL, ucenterProperties.getAppId(),
                    URLEncoder.encode(redirectUrl, "UTF-8"), // URLEncoder可以将字符串中的特殊符号或中文转为unicode编码的字符
                    state);
            return "redirect:"+URL;
        } catch (Exception e) {
            throw new GuliException(ResultCodeEnum.UNKNOWN_REASON);
        }
    }
    public  String changeJwt(Member member){
        JwtInfo jwtInfo = new JwtInfo();
        jwtInfo.setNickname(member.getNickname());
        jwtInfo.setAvatar(member.getAvatar());
        jwtInfo.setId(member.getId());
        String token = JwtHelper.createToken(jwtInfo);
        return "redirect:http://localhost:3000?token="+token;
    }
}

